﻿using Microsoft.WindowsAzure.Storage.Table;
using Microsoft.WindowsAzure.Storage.Table.DataServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Quiz.Model.Data
{
    public class QuizSetDataContext : TableServiceContext
    {
        static bool Initialized = false;
        public const string CandidateEntityName = "Candidate";
        public const string QuestionEntityName = "Question";
        public const string AnswerSetEntityName = "AnswerSet";
        public const string CandidateResponseEntityName = "CandidateResponse";
        CloudTableClient _client;
        public QuizSetDataContext(CloudTableClient client)
            : base(client)
        {
            _client = client;
            if (!Initialized)
            {
                CreateIfNotExists(client);
            }
        }
        public void CreateIfNotExists(CloudTableClient client)
        {
            string[] tables = new string[] { CandidateEntityName, QuestionEntityName, AnswerSetEntityName, CandidateResponseEntityName };
            Task task = new Task(() =>
            {
                tables.ToList().ForEach(t =>
                {
                    var table = client.GetTableReference(t);
                    table.CreateIfNotExists();
                });
            });
            task.Start();
        }
        public IQueryable<Candidate> Candidates
        {
            get
            {
                return CreateQuery<Candidate>(CandidateEntityName);
            }
        }
        public IQueryable<Question> Questions
        {
            get
            {
                return CreateQuery<Question>(QuestionEntityName);
            }
        }
        public IQueryable<AnswerSet> AnswerSets
        {
            get
            {
                return CreateQuery<AnswerSet>(AnswerSetEntityName);
            }
        }
        public IQueryable<CandidateResponse> CandidateResponses
        {
            get
            {
                return CreateQuery<CandidateResponse>(CandidateResponseEntityName);
            }
        }
    }
}
